package com.jt.chapter02.config;

import com.jt.chapter02.service.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author jiang tao
 * @date 2022/1/6
 * @description:
 **/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyUserDetailsService userDetailsService;

//    @Autowired
//    private  MyAuthenticationProvider myAuthenticationProvider;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
    //                /login 允许所有用户访问
                    .antMatchers("/login").permitAll()
    //                除上述提到的接口，任何接口都需要权限认证
                    .anyRequest().authenticated()
              .and()
                .formLogin()
                .loginProcessingUrl("/login")
//                在这添加成功失败处理器失败，因此在下面
//                .successHandler(new FuryAuthenticationSuccessHandler())
//                .failureHandler(new FuryAuthenticationFailureHandler())
                .defaultSuccessUrl("/hello")
                .permitAll()
                .and()
                .addFilterAt(myUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class).cors();

    }

    public  MyUsernamePasswordAuthenticationFilter myUsernamePasswordAuthenticationFilter() throws Exception {
        MyUsernamePasswordAuthenticationFilter myUsernamePasswordAuthenticationFilter = new MyUsernamePasswordAuthenticationFilter();
        myUsernamePasswordAuthenticationFilter.setAuthenticationManager(authenticationManagerBean());
        myUsernamePasswordAuthenticationFilter.setFilterProcessesUrl("/login");
        myUsernamePasswordAuthenticationFilter.setAuthenticationSuccessHandler(new FuryAuthenticationSuccessHandler());
        myUsernamePasswordAuthenticationFilter.setAuthenticationFailureHandler(new FuryAuthenticationFailureHandler());
        return myUsernamePasswordAuthenticationFilter;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new CustomPasswordEncoder());
//       auth.authenticationProvider(myAuthenticationProvider);

    }






}
